'''
Company: TWL
Author: xue jian
Email: xuejian@kanzhun.com
Date: 2020-08-17 21:45:36
'''
'''
给定一个二叉树，判断它是否是高度平衡的二叉树。

本题中，一棵高度平衡二叉树定义为：

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7
返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

'''
from tree_node import *

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def recurse(root):
            if not root:
                return True, 0
            test_l, high_l = recurse(root.left)
            test_r, high_r = recurse(root.right)
            if not test_l or not test_r:
                return False, 0
            if abs(high_l-high_r)>1:
                return False, 0
            return True, max(high_r, high_l)+1
        re, l=recurse(root)
        return re


if __name__ == "__main__":
    solution = Solution()
    null = 'null'
    root = [3,9,20,null,null,15,7]
    for i,v in enumerate(root):
        root[i] = str(v)
    s = ','.join(root)
    # print(s)
    o_s = OfficialSerialize()
    root = o_s.deserialize(s)
    print(solution.isBalanced(root))